package utils;
import book.Book;
import com.bit.utils.FileUtils;
import java.time.LocalDate;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 殇
 * Date: 2025-07-17
 * Time: 12:49
 */
public class AnalyzingBook {

    //存储书籍到文件
    public void storeObject(Book[] books,String filename){
        //计算实际有多少本书
        int bookLen=0;
        for(int i=0;i<books.length;i++){
            if(books[i]!=null)
                bookLen++;
        }
        //遍历books，将其序列化
        StringBuilder jsonArray=new StringBuilder();
        for(int i=0;i<bookLen;i++){
            jsonArray.append(books[i].toJSON());
            if(i<bookLen-1)
                jsonArray.append("\n");
        }
        FileUtils.writeFile(jsonArray.toString(),filename);

    }

    //从文件中读数据
    public Book[] loadObject(String filename){
        String content=FileUtils.readFile(filename);
        //文件不存在||文件无内容
        if(content==null||content.isEmpty()){
            System.out.println(filename+" is not exist");
            return null;
        }
        String[] bookString=content.split("\n");
        int len=bookString.length;
        Book[] books=new Book[len];
        for(int i=0;i<len;i++) {
            books[i]=parseBookJson(bookString[i]);
        }
        return books;
    }

    //将读出的数据进行解析(将一本书籍构造成书籍对象)
    public Book parseBookJson(String json){
        if(json.isEmpty())
            return null;
        String[] pairs=json.split(",");

        //获得书籍属性
        int bookId = Integer.parseInt(pairs[0]);
        String title = pairs[1];
        String author = pairs[2];
        String category = pairs[3];
        int publishYear = Integer.parseInt(pairs[4]);
        boolean isBorrowed = Boolean.parseBoolean(pairs[5]);
        int borrowCount = Integer.parseInt(pairs[6]);
        LocalDate shelfDate = LocalDate.parse(pairs[7]);

        //构造书籍对象
        if (title != null && author != null && category != null && shelfDate !=null) {
            Book book = new Book(title, author, category, publishYear, shelfDate);
            book.setBorrowed(isBorrowed);
            book.setBorrowCount(borrowCount);
            book.setBookId(bookId);
            return book;
        }
        return null;
    }

    public static void main(String[] args) {
        Book[] books = new Book[4];
        books[0] = new Book("java", "gaobo", "编程", 1994, LocalDate.of(2023, 9, 24));
        books[1] = new Book("mysql", "lisi", "编程", 1999, LocalDate.of(2024, 2, 10));
        books[2] = new Book("php", "gaobo", "编程", 2020, LocalDate.of(2023, 9, 23));
        books[3] = new Book("西游记", "吴承恩", "⼩说", 2024, LocalDate.of(2023, 9,
                23));
        AnalyzingBook analyzingBook=new AnalyzingBook();
        analyzingBook.storeObject(books,"allbooks.txt");
        Book[] tmp=analyzingBook.loadObject("allbooks.txt");
        for(int i=0;i<tmp.length;i++)
            System.out.println(tmp[i].toString());
    }
}
